package com.bxs.command;

import com.bxs.IdsManager;
import com.bxs.global.CommandMsg;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.AbstractQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 命令管理器，用于接收输入的命令
 */
//"专门通过socket进行通信需要保证通信的可靠性，较麻烦，不实用，直接使用http进行通信"
@Deprecated
@Slf4j
public class CommandManager {
    // 命令接收队列(需要双方进行二次通信，不适用消息队列的方式)
    private BlockingQueue<CommandMsg> msgQueue = new LinkedBlockingQueue<>();

    // 通信socket
    private AtomicBoolean isShutdown = new AtomicBoolean(false);
    private ServerSocket serverSocket = null;
//    @Value("command-server-port")
    private Integer port = 8989;   // 命令绑定端口

    // ids引擎
    public IdsManager idsManager = null;

    // 命令管理器同样维护一个线程池
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue();
    public ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 15,
            5, TimeUnit.MINUTES, queue);

    public CommandManager(IdsManager idsManager) throws IOException {
        log.info("command server socket start...");
        serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(this.port));
        this.idsManager = idsManager;
        log.info("command server socket start finished...");
    }

    // 作为生产者存在，也就是本应用中的命令消息只有一个生产者
    public void startCommandListening() throws IOException {
        log.info("command server start listening...");
        Socket socket = null;
        while((socket = serverSocket.accept()) != null && !isShutdown.get()){
            System.out.println("receive command packet: " + socket.getInetAddress().getHostName() + " : " +  socket.getPort());
            // TODO，从socket中读取数据存储到通信队列中
            threadPoolExecutor.submit(new CommandHandlerThread(socket, idsManager));
        }
        if (isShutdown.get() && !serverSocket.isClosed()){
            serverSocket.close();
        }
    }

    // 关闭命令服务通信接口
    public void closeCommandServerSocket() throws IOException {
        log.info("开始关闭命令服务通信接口...");
        isShutdown.set(false);
        serverSocket.close();
        log.info("关闭命令服务通信接口完成");
    }

    // 获取命令服务器执行状态
    public boolean getCommandServerStatus(){
        return isShutdown.get();
    }

    // 获取一个命令消息（阻塞式,保证线程安全）
    public CommandMsg getCommand() throws InterruptedException {
        return msgQueue.take();
    }

    // 直接将消息放入到消息队列中
    public void addCommand(CommandMsg msg) throws InterruptedException {
        msgQueue.put(msg);
    }
}
